import { changeCount, getCartList, delSelect } from "@/api/cart";
import { Toast } from "vant";

export default {
  namespaced: true,
  state() {
    return {
      cartList: [],
    };
  },
  mutations: {
    setCartList(state, cartList) {
      state.cartList = cartList;
    },
    toggleCheck(state, id) {
      const goods = state.cartList.find((item) => item.goods_id === id);
      goods.isChecked = !goods.isChecked;
    },
    toggleAllCheck(state, flag) {
      state.cartList.forEach((item) => {
        item.isChecked = flag;
      });
    },
    changeCount(state, { goodsId, goodsNum }) {
      const goods = state.cartList.find((item) => item.goods_id === goodsId);
      goods.goods_num = goodsNum;
    },
  },
  actions: {
    async getCartAction(context) {
      const { data } = await getCartList();
      // 后台返回的数据中，不包含复选框的选中状态，为了实现将来的功能
      // 需要手动维护数据，给每一项，添加一个 isChecked 状态(标记当前商品是否选中)
      data.list.forEach((item) => {
        item.isChecked = true;
      });
      context.commit("setCartList", data.list);
    },
    // 改变购物车数量
    async changeCountAction(context, obj) {
      const { goodsId, goodsNum, goodsSkuId } = obj;
      // 先在本地修改，
      context.commit("changeCount", {
        goodsId,
        goodsNum,
      });
      // 再同步后台
      await changeCount(goodsId, goodsNum, goodsSkuId);
    },
    async delSelect(context) {
      const selCartList = context.getters.selCartList;
      const cartIds = selCartList.map((item) => item.id)
      await delSelect(cartIds);
      Toast("删除成功");
      // 重新获取购物车数据
      context.dispatch("getCartAction");
    }
  },
  getters: {
    cartTotal(state) {
      // 求所有的商品的累加总数
      return state.cartList.reduce((sum, item) => sum + item.goods_num, 0);
    },
    // 选中的商品项
    selCartList(state) {
      return state.cartList.filter((item) => item.isChecked);
    },
    // 选中的总数
    selCount(state, getters) {
      return getters.selCartList.reduce((sum, item) => sum + item.goods_num, 0);
    },
    // 选中的总价
    selPrice(state, getters) {
      return getters.selCartList
        .reduce(
          (sum, item) => sum + item.goods_num * item.goods.goods_price_min,
          0
        )
        .toFixed(2);
    },
    // 是否全选
    isCheckAll(state) {
      return state.cartList.every((item) => item.isChecked);
    },
  },
};
